import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

void main() {
  // Material--根组件，可以配置页面和标题
  // Scaffold风格组件
  // 1. appBar配标题栏
  // 2. body 内容
  runApp(MaterialApp(
    title: '页签栏标题',
    // 配置页面
    // Scaffold是一个页面组件，可以配出顶部栏，正文，底部tab栏，悬浮按钮，抽屉
    home: Scaffold(
      appBar: AppBar(
        title: Text('你好'),
        backgroundColor: Colors.red,
        // 左侧的按钮
        leading: Icon(Icons.home),
        // 右侧的按钮
        actions: [Icon(Icons.share)],
      ),
      // 配正文主体部分
      // body: MyBody(age: 18),
      // 网络图片
      // body: Image.network(
      //     'https://yanxuan-item.nosdn.127.net/e529b6ab111ade9da9314867f98d360f.png'),
      // 本地图片 需要先配置pubspec.yaml文件
      // body: Image.asset(
      //   'qiche.png',
      //   width: 100,
      //   height: 100,
      //   fit: BoxFit.fill,
      // ),
      // body: Container(
      //   width: 300,
      //   height: 500,
      //   color: Colors.red,
      //   child: Column(
      //     // 主轴方向
      //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //     // 交叉轴方向
      //     crossAxisAlignment: CrossAxisAlignment.start,
      //     children: [
      //       Text('我是文本'),
      //       Text('我是文本'),
      //     ],
      //   ),
      // ),
      // body: TestRow(),
      // body: ExpandedComp2(),
      body: DioDemo(),
      //  配出底部的tab栏
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(
              icon: Icon(Icons.settings), label: 'Settings'),
        ],
        currentIndex: 0,
        onTap: (index) {},
      ),
      // 悬浮按钮，默认在右下角
      floatingActionButton: Icon(Icons.add),
    ),
    debugShowCheckedModeBanner: false,
  ));
}

class ExpandedComp2 extends StatelessWidget {
  const ExpandedComp2({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Expanded扩展'),
        backgroundColor: Colors.pink,
      ),
      body: Center(
        child: Container(
          height: 100,
          color: Colors.red,
          padding: const EdgeInsets.all(10),
          child: Row(
            children: [
              Image.network(
                'https://yanxuan-item.nosdn.127.net/afd6199278a5b8fd783bc4947960fabc.jpg',
                width: 86,
              ),

              // 问题：文字超出了父组件的范围
              // 解决：使用Expanded弹性布局组件解决文字溢出的问题
              Expanded(
                child: Text('茶水分离杯耐热隔热玻璃杯 茶水分离杯耐热隔热玻璃杯'),
              ),

              // 解决：使用Expanded弹性布局组件解决文字溢出的问题
              const Expanded(
                child: Text('茶水分离杯耐热隔热玻璃杯 茶水分离杯耐热隔热玻璃杯'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class TestRow extends StatelessWidget {
  const TestRow({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 300,
      height: 100,
      margin: EdgeInsets.all(10),
      color: Colors.red,
      child: Row(
        children: [
          Container(
            width: 50,
            height: 100,
            color: Colors.blue,
          ),
          // 默认占满剩余空间
          Expanded(
            child: Container(
              color: Colors.red,
            ),
          ),
          Expanded(
            child: Container(
              width: 50,
              height: 100,
              color: Colors.blue,
            ),
            // 占满剩余空间的比例
            flex: 2,
          )
        ],
      ),
    );
  }
}

// 快捷键 fstless
// 封装无状态组件--不会数据驱动视图
// 继承无状态组件StatelessWidget
class MyBody extends StatelessWidget {
  int? age;
  MyBody({super.key, this.age});

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 300,
        height: 500,
        // margin: EdgeInsets.all(10),//外边距
        // margin: EdgeInsets.symmetric(vertical: 10, horizontal: 100),
        // margin: EdgeInsets.fromLTRB(50, 100, 20, 50),
        margin: EdgeInsets.only(top: 10),
        padding: EdgeInsets.all(10), //内边距
        // color: Colors.red, //color属性和decoration中的color只能同时用一个
        // decoration: BoxDecoration(color: Colors.red),
        child: Text(
          '《春宵》 苏轼 \n 春宵一刻值千金，花有清香月有阴。\n 歌管楼台声细细，秋千院落夜沉沉。',
          style: TextStyle(
              fontSize: 20,
              color: Colors.white,
              overflow: TextOverflow.ellipsis),
          maxLines: 2, //最大行数
          strutStyle: StrutStyle(leading: 10), //行高
        ), //文字的位置
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.red,
          border: Border.all(color: Colors.blue, width: 2),
          borderRadius: BorderRadius.circular(10), //圆形
          // borderRadius: BorderRadius.only(
          //     topLeft: Radius.circular(50), bottomRight: Radius.circular(50)),
        ));
  }
}
// 快捷键 fstful
// 封装有状态组件--会数据驱动视图
// 继承有状态组件StatefulWidget

// 组件的生命周期--只有有状态组件才会有生命周期
class Main extends StatefulWidget {
  const Main({Key? key}) : super(key: key);
// 创建组件事调用
  @override
  _MainState createState() {
    print('创建');
    return _MainState();
  }
}

class _MainState extends State<Main> {
  @override
  void didUpdateWidget(covariant Main oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    print('更新');
  }

  @override
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    print('依赖改变');
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('初始化');
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print('销毁');
  }

  int age = 18;
  @override
  Widget build(BuildContext context) {
    print('构建');
    return Center(
      // 不是所有的组件都支持事件，TextButton
      child: TextButton(
          onPressed: () {
            // 数据驱动视图必须调用setState
            setState(() {
              age++;
            });
            print(age);
          },
          child: Text('我今年$age岁')),
    );
  }
}

class DioDemo extends StatefulWidget {
  const DioDemo({super.key});

  @override
  State<DioDemo> createState() => _DioDemoState();
}

class _DioDemoState extends State<DioDemo> {
  @override
  void initState() {
    // 获取订单列表数据
    loadData();
    super.initState();
  }

  List _orderList = [];
  // 演示dio插件的基本使用
  void loadData() async {
    // 1. 创建http client
    Dio dio = Dio();

    // 2. 发送网络请求，得到响应
    Response response =
        await dio.get('https://mock.boxuegu.com/mock/1172/orders');
    // 3. 提取订单列表数据
    print(response.data);
    setState(() {
      _orderList = response.data;
    });
  }

  /// 生成订单状态的方法
  String getOrderState(int state) {
    String orderState = '待付款';
    switch (state) {
      case 1:
        orderState = '待付款';
        break;
      case 2:
        orderState = '待发货';
        break;
      case 3:
        orderState = '待收货';
        break;
      case 4:
        orderState = '待评价';
        break;
      default:
        orderState = '其他';
    }

    return orderState;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('订单列表页'),
      ),
      body: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          // 读取当前item需要的数据
          Map orderInfo = _orderList[index];

          return Container(
            padding: const EdgeInsets.all(10.0),
            color: Colors.white,
            child: Column(
              children: [
                // 1. 订单创建时间+订单状态
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 创建时间
                    Text(
                      orderInfo['createTime'],
                      style: const TextStyle(
                          color: Color(0xFF666666), fontSize: 13),
                    ),
                    // 状态
                    Text(
                      getOrderState(orderInfo['orderState']),
                      style: const TextStyle(
                          color: Color(0xFFFF9240), fontSize: 13),
                    ),
                  ],
                ),
                // 2. 商品图片+名称+数量+规格+单价
                Padding(
                  padding: const EdgeInsets.only(top: 10.0),
                  child: Row(
                    children: [
                      // 图片
                      Image.network(
                        orderInfo['image'],
                        width: 86.0,
                        height: 86.0,
                      ),
                      // 名称+数量+规格+单价
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(left: 10.0),
                          child: Column(
                            // 保证名称+数量+规格+单价居左对齐
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 名称+数量
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  // 名称
                                  Expanded(
                                    child: Text(
                                      orderInfo['name'],
                                      style: const TextStyle(
                                          color: Color(0xFF262626),
                                          fontSize: 14),
                                    ),
                                  ),
                                  // 数量
                                  Padding(
                                    padding: const EdgeInsets.only(left: 10.0),
                                    child: Text(
                                      'x ${orderInfo['totalNum']}',
                                      style: const TextStyle(
                                          color: Color(0xFF262626),
                                          fontSize: 14),
                                    ),
                                  ),
                                ],
                              ),
                              // 规格
                              Padding(
                                padding: const EdgeInsets.only(top: 6.0),
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: const Color(0xFFF1F1F1),
                                    borderRadius: BorderRadius.circular(2.0),
                                  ),
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 3, horizontal: 5),
                                  child: Text(
                                    orderInfo['attrsText'],
                                    style: const TextStyle(
                                        color: Color(0xFF888888),
                                        fontSize: 12.0),
                                  ),
                                ),
                              ),
                              // 单价
                              Padding(
                                padding: const EdgeInsets.only(top: 6.0),
                                child: Text(
                                  '¥${orderInfo['curPrice']}',
                                  style: const TextStyle(
                                      color: Color(0xFF262626), fontSize: 14.0),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // 3. 合计
                Padding(
                  padding: const EdgeInsets.only(top: 10.0),
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: Text(
                      '合计：¥${orderInfo['curPrice'] * orderInfo['totalNum']}',
                      style: const TextStyle(
                          color: Color(0xFF262626), fontSize: 14.0),
                    ),
                  ),
                ),
                // 4. 再次购买
                Padding(
                  padding: const EdgeInsets.only(top: 10.0),
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border.all(
                            color: const Color(0xFF666666), width: 0.5),
                        borderRadius: BorderRadius.circular(2.0),
                      ),
                      padding: const EdgeInsets.symmetric(
                          vertical: 4, horizontal: 8),
                      child: const Text(
                        '再次购买',
                        style:
                            TextStyle(color: Color(0xFF666666), fontSize: 14.0),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return Container(height: 8.0, color: const Color(0xFFF7F7F8));
        },
        itemCount: _orderList.length,
      ),
    );
  }
}
